package com.sanpu.kxe.business.trade.presenter;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.sanpu.kxe.business.trade.bean.PayOrderOutput;
import com.sanpu.kxe.business.trade.bean.PayStatusOutput;
import com.sanpu.kxe.business.trade.contract.PaymentQRcodeContract;
import com.sanpu.kxe.business.trade.model.TradeModel;
import com.sanpu.kxe.business.trade.provider.TradeOpenProvider;
import com.sanpu.kxe.jump.shareutil.ShareUtil;
import com.sanpu.kxe.jump.shareutil.share.ShareListener;
import com.sanpu.kxe.jump.shareutil.share.SharePlatform;
import com.sanpu.kxe.module.dialog.MaterialDialog;
import com.sanpu.kxe.module.dialog.interfaces.OnBtnClickL;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.io.File;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：付款二维码等待扫码页面(扫码收款)
 * Created by 薛勇军 on 2019/3/20.
 */

public class PaymentQRcodePresenter implements PaymentQRcodeContract.Presenter {

    private PaymentQRcodeContract.View mView;

    private CompositeSubscription mSubscription;

    private String orderNo;

    private boolean isUpgrade;

    private int mIndex = 0;

    public PaymentQRcodePresenter(PaymentQRcodeContract.View mView, boolean isUpgrade) {
        this.mView = mView;
        this.isUpgrade = isUpgrade;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void payOrder(String amount, String appCnlConfId, String vipOpenId) {
        mView.showLoadingDialog(true, "生成二维码中...");
        Subscription subscription = TradeModel.getInstance().payOrder(amount, appCnlConfId, vipOpenId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PayOrderOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        ToastUtil.showTextViewPrompt("二维码获取失败！");
                    }

                    @Override
                    public void onNext(PayOrderOutput payOrderOutput) {
                        if (payOrderOutput != null) {
                            orderNo = payOrderOutput.getOrderNo();
                            mView.showDataView(payOrderOutput);
                            getTranPayStatus();
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void getTranPayStatus() {
        try {
            Subscription subscription = Observable.interval(10, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                    if (mIndex == 10 || TextUtils.isEmpty(orderNo)) {
                        return;
                    }
                    Subscription pSubscription = TradeModel.getInstance().findTranPayStatus(orderNo)
                            .subscribeOn(Schedulers.io())
                            .unsubscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<PayStatusOutput>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(PayStatusOutput payStatusOutput) {
                                    if (payStatusOutput != null && payStatusOutput.isSuccess()) {
                                        TradeOpenProvider.getInstance().openPaySuccessActivity(
                                                mView.getContext(), isUpgrade, payStatusOutput.getAmount(),
                                                payStatusOutput.getOrderTime());
                                    }
                                }
                            });
                    mSubscription.add(pSubscription);
                    mIndex++;
                }
            });
            mSubscription.add(subscription);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveImage(final Bitmap mClipScreen, final String payValue) {
        final MaterialDialog dialog = new MaterialDialog(mView.getContext());
        dialog.title("提示").content("保存这个二维码图片吗？").btnText("确定", "取消").show();
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                File result = FileUtil.saveImageToGallery(mView.getContext(), mClipScreen);
                ToastUtil.showTextViewPrompt(result != null ?
                        "图片保存成功, 请用" + payValue + "扫描付款。" : "图片保存失败");
                dialog.dismiss();
            }}, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    dialog.dismiss();
                }
            }
        );
    }

    @Override
    public void shareImage(Bitmap mClipScreen, final @SharePlatform.Platform int module) {
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                ToastUtil.showTextViewPrompt("分享成功");
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.showTextViewPrompt(e.getMessage());
            }

            @Override
            public void shareCancel() {
            }
        };
        ShareUtil.shareImage(mView.getContext(), module, mClipScreen, shareListener);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
